const { Controller } = require('egg');
const jwt = require('jsonwebtoken');
const { CozeAPI, COZE_CN_BASE_URL } = require('@coze/api');
const {getBotInfo}  = require('../api/coze')
const {getAgentToken} = require("../api/common");
class CozeController extends Controller {

  /**
   * 通过会话 ID 查看会话信息。
   */
  async getConversationById() {
    const { ctx, app } = this;
    const { conversation_id } = ctx.request.query;

    const ATRes = await getAgentToken(this,{conversation_id});
    if(!ATRes.success){
      ctx.body = ATRes;
      return;
    }
    const agent_access_token = ATRes.data;
    const client = new CozeAPI({
      baseURL: COZE_CN_BASE_URL,
      token: agent_access_token,
    });
    const conversation = await client.conversations.retrieve(conversation_id);
    ctx.body = {
      success: true,
     data: conversation
    }
  }

  /**
   * 获取我的最新会话
   */
  async getMyLastConversation() {
    const { ctx, app } = this;

    const {bot_id} = ctx.request.body;
    if (!bot_id) {
      ctx.body = {
        success: false,
        message: '请选择智能体'
      };
    }

    // 倒序
    const conversations = await app.mysql.select('conversations', {
      where: { bot_id: bot_id, user_id: ctx.currentUser.id },
      orders: [['created_at', 'desc']]
    });
    if (conversations.length > 0) {
      ctx.body = {
        success: true,
        data: conversations[0]
      };
      return;
    }

    const ATRes = await getAgentToken(this,{bot_id});
    if(!ATRes.success){
      ctx.body = ATRes;
      return;
    }
    const agent_access_token = ATRes.data;
    const client = new CozeAPI({
      baseURL: COZE_CN_BASE_URL,
      token: agent_access_token,
    });
    const conversation = await client.conversations.create({
      bot_id:bot_id,
    })
    conversation['conversation_id'] = conversation.id;
    const conversationId = conversation.id; // 会话ID
    await app.mysql.insert('conversations', {
      user_id: ctx.currentUser.id,
      conversation_id: conversationId,
      bot_id: bot_id,
      created_at: new Date(),
      last_section_id: conversation.last_section_id,
    })
    ctx.body = {
      success: true,
      data: conversation
    };
  }

  /**
   * 创建一个新会话。
   */
  async createConversation(){
    const { ctx, app } = this;

    const {bot_id} = ctx.request.body;
    const ATRes = await getAgentToken(this,{bot_id});
    if(!ATRes.success){
      ctx.body = ATRes;
      return;
    }
    const agent_access_token = ATRes.data;
    const client = new CozeAPI({
      baseURL: COZE_CN_BASE_URL,
      token: agent_access_token,
    });
    if (!bot_id) {
      ctx.body = {
        success: false,
        message: '请选择智能体'
      };
    }
    const conversation = await client.conversations.create({
      bot_id:bot_id,
    })
    const conversationId = conversation.id; // 会话ID
    app.mysql.insert('conversations',{
      user_id:ctx.currentUser.id,
      conversation_id:conversationId,
      bot_id:bot_id,
      created_at:new Date(),
      last_section_id:conversation.last_section_id,
    })
    ctx.body = {
      success: true,
      data: conversation
    };

  }

  /**
   * 获取全部 空间、智能体接口
   */
  async getAllSpaceAndBot() {
    const {ctx, app} = this;
    const client = new CozeAPI({
      baseURL: COZE_CN_BASE_URL,
      token: ctx.currentUser.coze_access_token,
    });
    const {page_size, page_number} = ctx.request.query;
    const access_token = ctx.currentUser.coze_access_token;
    console.log(access_token);
    // 调用空间列表接口
    const workspacesRes = await client.workspaces.list({
      page_size: page_size || 20,  // 每页数量，默认20
      page_number: page_number || 1  // 页码，从1开始
    });
    if (workspacesRes.workspaces) {
      for (const workspace of workspacesRes.workspaces) {
        const workspaceId = workspace.id;
        const resultBotsRes = await client.bots.list({
          space_id: workspaceId,
          page_size: page_size || 20,  // 每页数量，默认20
          page_number: page_number || 1  // 页码，从1开始
        })

        // 判断每个智能体 是否已存在
        for (const bot of resultBotsRes.space_bots) {
          const botId = bot.bot_id;
          const botRes = await app.mysql.get('agents', {
            bot_id: botId,
          });
          //如果已存在，则标记
          if (botRes) {
            bot['is_exist'] = 1;
          }else{
            bot['is_exist'] = 0;
          }
        }
        workspace['bots'] = resultBotsRes.space_bots;
      }
    }
    ctx.body = {
      success: true,
      data: workspacesRes.workspaces
    };
  }





  /**
    * 查看空间列表
    * https://www.coze.cn/open/docs/developer_guides/list_workspace
    */
  async getWorkspaceList() {
    const { ctx, app } = this;
    const { page_size, page_number } = ctx.request.query;
    const access_token= ctx.currentUser.coze_access_token;
    console.log(access_token);
        
     // 调用空间列表接口
      const result = await ctx.curl('https://api.coze.cn/v1/workspaces', {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${access_token}`,
          'Content-Type': 'application/json'
        },
        data: {
          page_size: page_size || 100,  // 每页数量，默认20
          page_number: page_number || 1  // 页码，从1开始
        },
        dataType: 'json',
        timeout: 10000,
      });

      console.log('Workspace list response:', result.data);

      if (result.status === 200) {
        ctx.body = {
          success: true,
          data: result.data
        };
      } else {
        ctx.status = result.status;
        ctx.body = {
          success: false,
          message: '获取空间列表失败',
          error: result.data
        };
      }
  }

  /**
   * 查看智能体列表
   *
   */
  async getBotsList() {
    const { ctx, app } = this;
    const { page_size,page_number,space_id } = ctx.request.query;
    const access_token = ctx.currentUser.coze_access_token;
    try {
      // 调用智能体列表接口
      const result = await ctx.curl('https://api.coze.cn/v1/space/published_bots_list', {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${access_token}`,
          'Content-Type': 'application/json'
        },
        data: {
          space_id:space_id,
          page_size: page_size||100,  // 每页数量，默认100
          page_number:page_number|| 1  // 页码，从1开始
        },
        dataType: 'json',
        timeout: 10000,
      });

      console.log('Bots list response:', result.data);

      if (result.status === 200) {
        ctx.body = {
          success: true,
          data: result.data
        };
      } else {
        ctx.status = result.status;
        ctx.body = {
          success: false,
          message: '获取智能体列表失败',
          error: result.data
        };
      }
    } catch (error) {
      ctx.logger.error('Get bots list error:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '服务器错误',
        error: error.message
      };
    }
  }

  /**
   * 获取智能体详情配置；
   * 包括开场白
   * https://api.coze.cn/v1/bot/get_online_info
   * bot_id
   */
  async getBotInfo() {
    const { ctx, app } = this;
    const { bot_id } = ctx.request.query;

    const res = await getAgentToken(this,{bot_id});
    if(!res.success){
      ctx.body = {
        success: false,
        message: res.message
      };
      return;
    }
    const access_token = res.data;
    // 调用智能体详情接口
    const result = await getBotInfo(bot_id,access_token)
    if(result.code ===0){
      ctx.body = {
        success: true,
        message: result.msg,
        data: result.data
      };
    }
    else{
      ctx.body = {
        success: false,
        message: result.msg
      };
    }
  }
}

module.exports = CozeController;
